package b.pay.impl

import java.net.URI

import com.lightbend.lagom.internal.scaladsl.registry.{RegisteredService, ServiceRegistry}
import com.lightbend.lagom.scaladsl.api.Descriptor.Call
import com.lightbend.lagom.scaladsl.api.ServiceLocator
import com.lightbend.lagom.scaladsl.api.transport.NotFound
import com.lightbend.lagom.scaladsl.client.CircuitBreakerComponents
import com.lightbend.lagom.scaladsl.devmode.LagomDevModeComponents
import com.lightbend.lagom.scaladsl.server.{LagomApplication, LagomApplicationContext, LagomApplicationLoader}
import com.typesafe.config.ConfigFactory
import play.api.Configuration

import scala.collection.immutable.{Map, Seq}
import scala.concurrent.Future
import scala.util.{Failure, Success}

/**
  * Created by lenovo on 2017/1/24.
  */
class C收付ApplicationLoader extends LagomApplicationLoader {
  override def loadDevMode(context: LagomApplicationContext): LagomApplication =
    new AC收付Application(context) with LagomDevModeComponents
    {
      def locate(name: String, serviceCall: Call[_, _]): Future[Option[URI]] = {
        require(name != ServiceRegistry.ServiceName)
        log.info(s"Locating service name=[$name] ...")
        // List the third services
        val locations: Future[Seq[RegisteredService]] = {
          serviceRegistry.registeredServices.invoke().map { services =>
            services.filter(_.name != name).filter(_.name.startsWith(name))
          }
        }
        locations.onComplete {
          case Success(addresses) =>
            addresses.foreach { a =>
              log.info(s"XXX Service name=[$name] can be reached at address=[$a]")
            }
            if (addresses.isEmpty)
              log.warn(s"Service name=[$name] was not found. Hint: Maybe it was not registered? XXX")
          case Failure(e) =>
            log.warn(s"The service locator replied with an error when looking up the service name=[$name] address XXX", e)
        }
        serviceRegistry.lookup(name).invoke().map(Some.apply).recover {
          case notFound: NotFound => None
        }
      }
      override lazy val serviceLocator: ServiceLocator = new C第三方支付ServiceLocator4Dev(this, locate)
    }
  override def load(context: LagomApplicationContext): LagomApplication = new AC收付Application(context) with CircuitBreakerComponents {
    override def serviceLocator: ServiceLocator = new C第三方支付ServiceLocator(
      Map(
        "THIRD1" -> URI.create("http://0.0.0.0:9001"),
        "THIRD2" -> URI.create("http://0.0.0.0:9002")
      ),
      circuitBreakers
    )
  }
}
